﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using ScFramework.Core;
using System;
using UnityEditor.ShortcutManagement;
using System.Linq;
using System.IO;

/*

public  class EntityEditEditor :Editor
{
//    [MenuItem("Tools/EntityEdit/RunPrefabCompoentCheck")]
    public static List<GameObject> RunPrefabComponentCheck()
    {
        Dictionary<string, int> nameCnt = new Dictionary<string, int>();
        var list= Resources.LoadAll<GameObject>("Prefab/Component");
        foreach(var x in list)
        {
            if (nameCnt.ContainsKey(x.name))
            {
                Debug.LogError($"{x}:存在多个名称相同的组件预设");
            }
            nameCnt[x.name]=1;
            if (CheckPrefabComponentLegal(x,x,true) == false)
            {
                Debug.LogError($"{x}:组件预设中SComponent设置错误");
            } 
            
        //    Debug.Log()
        }
        Debug.Log("组件预设检测无错误");
        return new List<GameObject>(list);
    }
    private static readonly string ConstomPath = "Assets/Resources/Text/PrefabSetting/";


    static bool CheckPrefabComponentLegal(GameObject obj,GameObject root,bool isRoot=true)
    {
        if (isRoot)
        {

            if (obj.GetComponent<SGameObject>() == null)
            {
                return false;
            }
        }
        else
        {
            if (obj.GetComponent<SGameObject>() != null)
            {
                return false;
            }
        }
        if (isRoot)
        {
            if (PrefabUtility.IsOutermostPrefabInstanceRoot(obj)==false)
            {
                root = null;
            }
        }
        if (isRoot==false && PrefabUtility.GetOutermostPrefabInstanceRoot(obj)!=root)
        {
            return false;
        }
        int cnt = obj.transform.childCount;
        for (int i = 0; i < cnt; i++)
        {
            if (CheckPrefabComponentLegal(obj.transform.GetChild(i).gameObject,root,false) == false)
            {
                return false;
            }
        }
        return true;

    }
  //  [RuntimeInitializeOnLoadMethod]
  //  [MenuItem("Tools/EntityEdit/GenPrefabFiles")]
    public static void GenPrefabFiles()
    {
   //     EntityUtilities.InitUseableComponent();

        FileExtensions.DeleteAllFile(ConstomPath);

        var map = GameObject.Find("Map");
        var list = RunPrefabComponentCheck();
        int cnt = map.transform.childCount;
        for (int i = 0; i < cnt; i++)
        {

            var entity = GenPrefab(map.transform.GetChild(i), list);
            //  JsonUtility.ToJson(entity);
            
            JsonUtil.SerializeToFile(entity, ConstomPath + entity.EntityName + ".json");

            EditorUtility.SetDirty(map.transform.GetChild(i));
            AssetDatabase.SaveAssets();
        }
        AssetDatabase.Refresh();
        EntityUtilities.InitEntityDefaultSetting();
    }
    static List<GameObject>GetBodyGameObject(Transform trans)
    {
        Debug.Assert(trans.GetComponent<SGameObject>());
        List<GameObject> ans = new List<GameObject> { trans.gameObject };
        int cnt = trans.childCount;
        for(int i = 0; i < cnt; i++)
        {
            if (trans.GetChild(i).GetComponent<SGameObject>())
            {
                ans.AddRange(GetBodyGameObject(trans.GetChild(i)));
            }
        }
        return ans;
    }
    static EntityPrefab GenPrefab(Transform transform, List<GameObject> list)
    {
        UInt16 c = 0;
        EntityPrefab entity = new EntityPrefab();
        var name = GenPrefabFile(transform, list, 0, ref c, ref entity);
        entity.EntityName = name;

        Entity e = EntityUtilities.CreateEntityAndInit(GetBodyGameObject(transform), entity.ComponentPrefabs,parent:transform.parent);


        for(ushort i = 0; i < e.CompCnt; i++)
        {
            var comp = e.GetComponent(i);
            for(ushort j = 0; j < comp.ValueCnt; j++)
            {
                if (comp.IsValuePure(j) == false)
                {
                    var nv = comp.GetInstanceValue(j);
                    if(ValueUtil.EqualsDefault(nv)==false)
                    {
                        entity.ComponentValueList[i].Values.Add(new PrefabValuePair {ID=j,ValuePair=new PrefabValue(nv) });
                    }
                }
            }
        }



        return entity;

    }
    static string GenPrefabFile(Transform transform,List<GameObject>list,UInt16 parentID,ref UInt16 compCnt,ref EntityPrefab entity)
    {
        try
        {
            var editCache = GameObject.FindObjectOfType<EditCache>().ValueCaches;

            if (PrefabUtility.IsOutermostPrefabInstanceRoot(transform.gameObject)==false)
            {
                throw new Exception("此物体不为组件预设");
            }

            var prefabname = PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(transform.gameObject).Split('/').Last().Split('.')[0];
            if (compCnt == 0)
            {
                entity.EntityName = transform.name;
                entity.ComponentPrefabs = new List<ComponentPrefab>();
            }
            Debug.Log(prefabname);


            if (list.Find(s => s.name == prefabname) == null)
            {
                throw new Exception("该组件预设未找到");
            }
            if (transform.GetComponent<SGameObject>() == null)
            {
                throw new Exception("未找到SGameObject");
            }

            var comp = new ComponentPrefab();
            comp.ParentID = parentID;
            comp.PrefabPath = PrefabUtility.GetPrefabAssetPathOfNearestInstanceRoot(transform.gameObject).Substring(34).Split('.')[0];
            //   comp.ComponentType = transform.GetComponent<SGameObject>().GetType();
            UInt16 thisId = compCnt;
            entity.ComponentPrefabs.Add(comp);
            var sg = transform.GetComponent<SGameObject>();
            while (transform.GetComponent<SComponent>() != sg)
            {
                Debug.Log("move up");
                UnityEditorInternal.ComponentUtility.MoveComponentUp(sg);
            }
            
            var clis =new List<SComponent>( transform.GetComponents<SComponent>());


            foreach(var x in clis)
            {
                compCnt++;
                entity.ComponentValueList.Add(new ValueList { TypeName= x.GetType().Name, Values= GetCompValue(x,editCache) });
            }


            int cnt = transform.childCount;
            for(int i = 0; i < cnt; i++)
            {
                if (transform.GetChild(i).GetComponent<SGameObject>())
                {
                    GenPrefabFile(transform.GetChild(i), list, thisId,ref compCnt,ref entity);
                }
                else
                {
                   if(CheckPrefabComponentLegal(transform.GetChild(i).gameObject, transform.gameObject,false) == false)
                    {
                        throw new Exception($"子物体{transform.GetChild(i)}不合法");
                    }
                }
            }

            return transform.gameObject.name;
        }
        catch(Exception e)
        {
            Debug.LogError($"{ transform}" + e);
            return null;
        }

    }
    static List<PrefabValuePair> GetCompValue(SComponent comp,List<ValueCache>valueCaches)
    {
         
        return valueCaches.FindAll(s =>
        {            return s.comp == comp;
        }).ConvertAll(s =>s.value);
    }
}
*/